<template>
  <view class="booking">
    <view class="content">
      <view class="nav">
        <left-nav :data="list" :current="current" @change="navChange"></left-nav>
      </view>
      <scroll-view
        :scroll-into-view="toView"
        :scroll-with-animation="true"
        class="main"
        @scroll="(e) => debounce(scroll, 100)(e)"
        scroll-y
      >
        <view class="scroll_main">
          <view v-for="(item, index) in list" :id="'type' + index" :key="item.id">
            <view :id="'title' + index">
              <up-divider :text="item.kindName"></up-divider>
            </view>
            <card
              v-for="item2 in item.meals"
              :key="item2.id"
              :data="item2"
              @change="cardChange"
            ></card>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="bottom" v-if="showOrder">
      <view id="left_icon" class="left_icon" @click="showPop = !showPop"> </view>
      <view class="bottom_info">
        <view
          >共计：<text style="font-weight: bold; color: #fb3b26">{{ money }}</text
          >元</view
        >
        <view class="meal_kinds">{{
          selectMealKind ? `已点：${selectMealKind}` : '快来预定吧~'
        }}</view>
      </view>
      <view class="submit" @click="submitOrder(ruleFormRef)"> 确认预订 </view>
    </view>
  </view>

  <!-- 弹出层 -->
  <up-popup
    :show="showPop"
    mode="bottom"
    border-radius="20"
    closeable
    z-index="1"
    @close="showPop = false"
    :safe-area-inset-bottom="false"
  >
    <scroll-view class="pop_main" scroll-y>
      <view class="pop_title"> 已选菜品 </view>
      <view class="scroll_main">
        <view v-for="item in handleList" :key="item.id">
          <view v-if="item.meals.length">
            <up-divider :text="item.kindName"></up-divider>
          </view>
          <card
            v-for="item2 in item.meals"
            :key="item2.id"
            :data="item2"
            @change="cardChange"
          ></card>
        </view>
      </view>
      <up-divider></up-divider>
      <sar-form
        :model="form"
        ref="ruleFormRef"
        direction="horizontal"
        label-align="start"
        label-valign="center"
        star-position="right"
        :rules="rules"
        card
      >
        <sar-form-item label="配送地址" required name="orderAddress">
          <sar-picker-input
            v-model="form.orderAddress"
            placeholder="请选择配送地址"
            title="配送地址"
            :columns="showAddressList"
            @update:visible="
              (visible: boolean) => {
                showOrder = !visible;
              }
            "
            @update:model-value="(value: any) => {}"
          />
        </sar-form-item>
        <sar-form-item label="联系电话" required name="phone">
          <sar-input v-model="form.phone" clearable readonly />
        </sar-form-item>
        <sar-form-item label="联系人" required name="people">
          <sar-input v-model="form.people" clearable readonly />
        </sar-form-item>
        <sar-form-item label="配送时间" required name="orderTime">
          <sar-datetime-picker-input
            v-model="form.orderTime"
            type="hm"
            placeholder="配送时间"
            @update:visible="
              (visible: boolean) => {
                showOrder = !visible;
              }
            "
          />
        </sar-form-item>
        <sar-form-item label="备注">
          <sar-input v-model="form.orderRemark" type="textarea" show-count clearable />
        </sar-form-item>
      </sar-form>
    </scroll-view>
  </up-popup>
</template>

<script setup lang="ts">
  import leftNav from '@/components/nav/nav.vue';
  import card from '@/components/card/card.vue';
  import { debounce } from '@/utils/debounce';
  import { computed, nextTick, ref, reactive, watch } from 'vue';
  import { onReady } from '@dcloudio/uni-app';
  import { getMealByMealKind } from '@/services/mealkind';
  import type { MealKindType } from '@/types/mealkind';
  import type { MealType } from '@/types/meal';
  import type { AddressType } from '@/types/address';
  import { getAddressAPI } from '@/services/address';
  import { insertOrderAPI } from '@/services/order';
  import { type FormExpose, type FieldValidateError } from 'sard-uniapp';
  import { rules } from './vaild/vaildRules';
  import dayjs from 'dayjs';

  const showPop = ref(false);
  const titleH = ref<any[]>([]);
  const scrollH = ref(0);
  const toView = ref('');
  const current = ref(0);
  const list = ref<MealKindType[]>([]);
  const handleList = ref<MealKindType[]>([]);
  const addressList = ref<AddressType[]>([]);
  const showAddressList = ref([] as any[]);
  const ruleFormRef = ref<FormExpose>();
  const showOrder = ref(true);

  const form = reactive({
    orderAddress: '',
    phone: '',
    orderTime: undefined,
    orderRemark: '',
    people: '',
  });

  onReady(async () => {
    const res = await getMealByMealKind();
    const addressRes = await getAddressAPI();
    addressList.value = addressRes.data;
    addressList.value.forEach((item) => {
      showAddressList.value.push({
        label: `${item.address}-${item.name}-${item.phone}`,
        value: item.id,
      });
    });
    list.value = res.data;
    nextTick(() => {
      list.value.forEach((item, index) => {
        handleList.value.push({
          id: item.id,
          kindName: item.kindName,
          meals: [],
        });
        uni
          .createSelectorQuery()
          .select('#title' + index)
          .boundingClientRect()
          .exec((data: any) => {
            titleH.value.push(data[0]);
          });
      });
    });
  });

  const cardChange = (e: MealType) => {
    const mkIndex = handleList.value.findIndex((item) => item.id === e.mealKind);
    const mIndex = handleList.value[mkIndex].meals.findIndex((item) => item.id === e.id);
    if (!e.number && mIndex >= 0) {
      handleList.value[mkIndex].meals.splice(mIndex, 1);
      return;
    }
    if (mIndex >= 0) {
      handleList.value[mkIndex].meals[mIndex].number = e.number;
    } else {
      handleList.value[mkIndex].meals.push(e);
    }
  };

  const money = computed(() => {
    let totalMoney = 0;
    handleList.value.forEach((item) => {
      item.meals.forEach((meal) => {
        totalMoney = totalMoney + Number((parseFloat(meal.mealPrice) * meal.number).toFixed(2));
      });
    });
    return totalMoney;
  });

  const selectMealKind = computed(() => {
    const mkStr: string[] = [];
    handleList.value.forEach((item) => {
      if (item.meals.length) {
        mkStr.push(item.kindName);
      }
    });
    return mkStr.join('、');
  });

  const submitOrder = (formEl?: FormExpose) => {
    showPop.value = true;
    if (!money.value) {
      uni.showToast({
        icon: 'none',
        title: '暂无美食',
      });
      return;
    }
    if (!formEl) {
      return;
    }
    formEl
      .validate()
      .then(async () => {
        const res = await insertOrderAPI({
          ...form,
          orderText: JSON.stringify(handleList.value),
          orderPrice: money.value,
          orderTime: form.orderTime
            ? dayjs(form.orderTime).format('YYYY-MM-DD HH:mm') + ':00'
            : dayjs().format('YYYY-MM-DD HH:mm') + ':00',
        });
        if (res.code === 200) {
          formEl.reset();
          showPop.value = false;
        }
      })
      .catch((error: FieldValidateError[]) => {
        console.log('error submit!', error);
      });
  };

  /* 菜单滚动监听 */
  function scroll(e) {
    titleH.value.forEach((item, index) => {
      if (e.detail.scrollTop + item.height > item.top) {
        current.value = index;
      }
    });
    scrollH.value = e.detail.scrollTop;
  }

  function navChange(e) {
    current.value = e;
    getRightScrollDistance();
  }

  function getRightScrollDistance() {
    toView.value = 'title' + current.value;
  }

  watch(
    () => form.orderAddress,
    (newValue) => {
      if (!newValue) {
        return;
      }
      const { name, phone } = addressList.value.find((item) => item.id === newValue) as AddressType;
      form.people = name;
      form.phone = phone;
    },
  );
</script>

<style lang="scss">
  @import './styles/meal.scss';
</style>
